package Hibernate;
import org.hibernate.*;
import org.mindrot.jbcrypt.BCrypt;

import users.User;

import java.util.*;

public class HibernateControl {

	//liefert ein User-Objekt mit angegebener ID
	public static User getUser(String name) {
		User user = findUser(name);
		return user;
		
		
	}
	public static boolean passworttest(String name, String password){
		User user = findUser(name);
		if(user != null){
			return BCrypt.checkpw(password, user.getPassword());
		}else {
			return false;
		}
	
	}
	public static String passwordHash(String password){
		return BCrypt.hashpw(password, BCrypt.gensalt(10));
	}
 
	public static User findUser(String name){
		try{
		Session s = HibernateUtil.getSession();Transaction tx = s.beginTransaction();
		List usersL = s.createQuery("from User where name like '" +name+"'").list();
		User user = (User) usersL.iterator().next();
		tx.commit();
		return user;
		} catch (NoSuchElementException asd){
			User user=null;
			return user;
			
		}
		
	}
	
	//
	public static String makeSomeUsers(String name, String password) {
		User u1 = findUser(name);
		if(u1 == null){
			u1= new User();
			u1.name = name;
			u1.setPassword(passwordHash(password));

 
			Session s = HibernateUtil.getSession();
			Transaction tx = s.beginTransaction();

			s.save(u1);
			tx.commit();
			return "Erfolgreich registriert.";
		} else {
			return "User exisitiert bereits!";
		}
		
	}

 
	//Test-Main zum Testen der Methoden ohne Flex
	public static void main(String[] args) {
		//makeSomeUsers("asd","asd!");
		//System.out.println(passworttest("1234",1));
		//System.out.println(getUser(1).name);
	}
}